package nil.ed.livechat.timeshift.sync;

import com.google.inject.Inject;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import nil.ed.livechat.timeshift.sync.common.ConfigContext;
import nil.ed.livechat.timeshift.sync.ext.RedisSyncService;
import nil.ed.livechat.timeshift.utils.m3u8.FastDfsUtils;
import nil.ed.livechat.timeshift.utils.m3u8.MpegTsUtils;
import nil.ed.livechat.timeshift.utils.m3u8.TsInfo;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;

import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author delin10
 * @since 2020/6/26
 **/
@Slf4j
public class TsScheduledUpdateTask implements Runnable {

    @Inject
    private DelayQueue<UpdateMetaData> queue;

    private volatile boolean shutdown;

    @Inject
    private ConfigContext configContext;

    @Inject
    private RedisSyncService syncService;

    @Override
    public void run() {
        while (!shutdown) {
            try {
                UpdateMetaData metaData = queue.poll(3, TimeUnit.SECONDS);
                log.info("Update metadata: {}", metaData);
                if (metaData != null) {
                    String segBasePath = configContext.getBase() + "/"
                            + metaData.getName();
                    File segBaseFile = new File(segBasePath);
                    if (segBaseFile.exists()) {
                        File[] fs = segBaseFile.listFiles();
                        if (fs == null) {
                            continue;
                        }
                        List<File> candidateFiles = new LinkedList<>();
                        for (File f : fs) {

                            if (f.isFile() && f.getName().endsWith(".ts")) {
                                int seq = getSeq(f);
                                if (seq > metaData.index) {
                                    candidateFiles.add(f);
                                }
                            }
                        }
                        candidateFiles.sort(Comparator.comparingInt(this::getSeq));
                        log.info("Candidata list: {}", candidateFiles);
                        if (candidateFiles.size() > 1) {
                            Iterator<File> iterator = candidateFiles.iterator();
                            while (iterator.hasNext()) {
                                File f = iterator.next();
                                if (!iterator.hasNext()) {
                                    break;
                                }
                                String url = FastDfsUtils.upload(f);
                                TsInfo tsInfo = MpegTsUtils.getTsInfo(f.getAbsolutePath());
                                tsInfo.setName(metaData.getName());
                                tsInfo.setUrl(url);
                                System.out.println(tsInfo);
                                syncService.push(tsInfo);
                                metaData.index = getSeq(f);
                            }
                            metaData.setLastUpdateTime(System.currentTimeMillis());
                        }

                    }
                    if (System.currentTimeMillis() - metaData.getLastUpdateTime() < configContext.getMaxIdleTime()) {
                        metaData.setNextTime();
                        queue.put(metaData);
                        log.info("Update completed! {}", metaData);
                    }
                }
            } catch (InterruptedException ignore) { } catch (IOException | MyException e) {
                log.error("", e);
            }
        }
    }


    public int getSeq(File f) {
        String name = FilenameUtils.getName(f.getAbsolutePath());
        return Integer.parseInt(name.substring(0, name.indexOf('.')));
    }

    public void setShutdown(boolean shutdown) {
        this.shutdown = shutdown;
    }


    @ToString
    public static class UpdateMetaData implements Delayed {

        @Setter
        @Getter
        private String name;

        @Setter
        @Getter
        private int index;

        @Getter
        private long nextTime;

        @Setter
        @Getter
        private long interval;

        @Getter
        @Setter
        private long lastUpdateTime;

        public void setNextTime() {
            this.nextTime = System.currentTimeMillis() + interval;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return nextTime - System.currentTimeMillis();
        }

        @Override
        public int compareTo(Delayed o) {
            return Long.compare(getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
        }

    }

    public static void main(String[] args) {
        ConfigContext configContext = new ConfigContext();
        DelayQueue<UpdateMetaData> queue = new DelayQueue<>();
        UpdateMetaData metaData = new UpdateMetaData();
        metaData.setIndex(-1);
        metaData.setInterval(2 * 1000);
        metaData.setName("1");
        queue.put(metaData);
        new TsScheduledUpdateTask().run();
    }
}
